import { Radio, Tooltip, Button, Input, message } from 'antd';
import React, { useState, useEffect, useRef, useImperativeHandle } from 'react';
import Table from '../table/new-table';
import ProcessBarUpload from '../../../../components/Upload/ProcessBarUpload';
import MaterialUpload from '../../../../components/Upload/MaterialUpload';
import { BjyVideoListModalUpload } from '@/pages/pc/components/Upload';
import AddForVideoLibrary from '../AddForVideoLibrary';
import styles from './index.less';
import { allGet } from '@/services/pc';
import { flatArray, isRAR, isVideo } from '@/utils';

import { useHistory } from 'umi';
import classNames from 'classnames';
import { useModel } from '@@/plugin-model/useModel';
import { apiUrl } from '@/common/const';

export interface UploadInstance {
  getData: () => any;
}
const Index = React.forwardRef<UploadInstance, any>((props, ref) => {
  const { userInfo } = useModel('user');
  const [uploadConfig, setUploadConfig] = useState<any>({});
  const [current, setCurrent] = useState(1);
  const [materialType, setMaterialType] = useState<'本地上传' | '网盘地址'>('本地上传'); // 本地上传 | 网盘地址
  // 本地上传素材zip的值
  const zipUploadRef = useRef<any>([]);
  const [material, setMaterial] = useState<any>({});
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [urlVisible, setUrlVisible] = useState(false);
  const [initialValues, setInitialValues] = useState({});
  const [url, setUrl] = useState<string>();
  const { classid = 0 } = (useHistory().location as any)?.query;
  const tableRef = useRef<any>();
  const onMaterialTypeChange = (evt) => {
    setMaterialType(evt.target.value);
  };

  const onAddVideo = async (values) => {
    // console.log('onAddVideo', values);
    // setDataSource([...dataSource, ...values]);
    if (!values.length) {
      return false;
    }
    const response = await allGet({
      params: {
        mod: 'lesson',
        do: 'add',
        version: 'pc1.0',
        classid,
        polyvvids: values.map((item) => item.video_id).join(','),
      },
    });
    if (response.success) {
      init();
    }
    return response.success;
  };

  const othersParams = useRef<any>({});
  const isFirst = useRef(true);
  /**
   * 获取课程详情数据
   */
  const init = async () => {
    if (isFirst.current) {
      const uploadConfigResponse = await allGet({
        params: { mod: 'teacher', do: 'add', version: 'pc1.0' },
      });
      setUploadConfig(uploadConfigResponse);
      isFirst.current = false;
    }

    setLoading(true);
    const response = await allGet({
      params: { mod: 'course', do: 'post', version: 'pc1.0', classid /* classid */ },
    });
    if (response.success) {
      const { chapters = [] } = response.data;
      // const allCl = flatArray(chapters)
      //   .map(({ lid }) => lid)
      //   .filter((lid) => !!lid);
      const chapters_1: any[] = [];
      let othersLessons_1: any[] = [];
      chapters.forEach((item, index) => {
        if (Number(item.cid) === 0) {
          othersLessons_1 = (item.children ?? []).map((it, i, arr) => {
            if (i > 0) {
              it.beforeIndex = arr[i - 1].displayorder;
            }
            if (i < arr.length - 1) {
              it.afterIndex = arr[i + 1].displayorder;
            }
            return it;
          });
        }
        // } else {
        chapters_1.push({
          ...item,
          children: (item.children ?? []).map((it, i, arr) => {
            if (i > 0) {
              it.beforeIndex = arr[i - 1].displayorder;
            } else if (i < arr.length - 1) {
              it.afterIndex = arr[i + 1].displayorder;
            }
            return it;
          }),
        });
        // }
      });

      setDataSource([...chapters_1]);

      //  额外的参数记录
      othersParams.current.chapter_ids = [];
      othersParams.current.lesson_ids = [];
      if (chapters_1) {
        chapters_1.forEach((item) => {
          othersParams.current.chapter_ids.push(item.cid);
          if (item.children && Array.isArray(item.children)) {
            item.children.forEach((item) => {
              othersParams.current.lesson_ids.push(item.lid);
            });
          }
        });
      }
      if (othersLessons_1?.length) {
        othersLessons_1.forEach((item) => {
          othersParams.current.lesson_ids.push(item.lid);
        });
      }
      // let othersLessons = [...(chapters ?? [])].filter(({ cid }) => cid === 0)?.[0]?.children || [];
      // setDataSource([
      //   ...chapters
      //     .filter(({ cid }) => cid !== 0)
      //     .map((item) => ({ ...item, children: item.children || [] })),
      //   ...othersLessons,
      // ]);

      // 附件
      const files = response?.data?.files;
      setMaterial({
        attach:
          files?.attach?.map((file) => ({
            ...file,
            size: file.filesize,
            url: file.attachment,
            name: file.filename,
            uid: file.aid,
            status: 'done',
          })) || [],
        disk:
          files?.disk?.map((item) => ({
            ...item,
            name: item.filename,
            url: item.attachment,
            aid: item.attachid,
          })) || [],
      });

      // 素材本地上传zip
      if (files?.attach?.length > 0 && Array.isArray(files?.attach)) {
        setMaterialType('本地上传');
        const file = files.attach[0] || {};
        zipUploadRef.current = [
          {
            ...file,
            url: file.attachment,
            name: file.filename,
            uid: file.aid,
            status: 'done',
          },
        ];
      }
      // 素材网盘
      else if (files?.disk?.length > 0 && Array.isArray(files?.disk)) {
        const { attachment: url, aid } = files.disk[0] || {};
        setMaterialType('网盘地址');
        setWangpanUrl({
          url,
          aid,
        });
      }
    }

    setInitialValues(response);
    setLoading(false);
  };
  useEffect(() => {
    init();
  }, []);
  useEffect(() => {
    // console.log('dataSource-->', dataSource);
  }, [dataSource]);
  const auth = async () => {
    const response = await allGet({ params: { mod: 'polyv', do: 'uploadAuth', version: 'pc1.0' } });
    return { ...(response?.data || {}), ptime: response?.data?.ts };
  };
  const handleUploadSuccess = async (_, file) => {
    // await allGet({
    //   params: {
    //     mod: 'polyv',
    //     do: 'add',
    //     version: 'pc1.0',
    //     filename: file.name,
    //     filesize: file.size,
    //     polyvvid: file?.response?.vid,
    //     classid,
    //     createlesson: 1,
    //   },
    // });
    init();
  };

  const handleSucaiBeforeUpload = async (file) => {
    if (!isRAR(file.name)) {
      message.error('仅支持 zip/rar 格式');
      return false;
    }
    return true;
  };

  const [wangPanUrl, setWangpanUrl] = useState<any>({});
  const handleUploadWangpanUrl = async () => {
    const response = await allGet({
      params: {
        mod: 'swfupload',
        ac: 'course',
        field: 'disk',
        version: 'pc1.0',
        classid,
        uid: uploadConfig?.data?.space?.uid,
        hash: uploadConfig?.data?.swfconfig?.hash,
        url: wangPanUrl.url,
      },
    });
    if (response.success) {
      setWangpanUrl({
        ...wangPanUrl,
        aid: response.data?.attachid,
      });
    }
  };
  const handleWangpanUrlChange = (e) => {
    setWangpanUrl({
      ...wangPanUrl,
      url: e.target.value,
    });
  };

  const onAddVideoWithUrl = async () => {
    console.log(url);
    if (!url?.length) {
      return false;
    }
    const response = await allGet({
      params: {
        mod: 'lesson',
        do: 'add',
        version: 'pc1.0',
        classid,
        url,
      },
    });
    if (response.success) {
      message.success('添加成功');
      init();
      setUrl(undefined);
      setUrlVisible(false);
    }
  };

  const handleSucaiZIpUploadSuccess = async (_, file) => {
    zipUploadRef.current = file;
  };
  /**
   * 供父组件调用
   */
  useImperativeHandle(ref, () => ({
    init,
    getData: () => {
      const { attach, disk } = material;
      let attachIds = [];
      attachIds = attachIds.concat(
        attach?.filter((item) => item.aid)?.map((item) => item.aid) || [],
      );
      attachIds = attachIds.concat(disk?.filter((item) => item.aid)?.map((item) => item.aid) || []);
      // console.log(attachIds, 'attachIds');
      return {
        attach_ids: attachIds,
        ...othersParams.current,
        lesson_orders: tableRef.current?.getLessonOrders(),
      };
    },
  }));
  return (
    <div className={styles.container}>
      {/* 素材 */}
      <MaterialUpload
        action={apiUrl}
        payload={{
          mod: 'swfupload',
          ac: 'course',
          field: 'attach',
          classid,
          version: 'pc1.0',
          uid: uploadConfig?.data?.space?.uid,
          hash: uploadConfig?.data?.swfconfig?.hash,
        }}
        diskPayload={{
          classid,
          version: 'pc1.0',
          uid: uploadConfig?.data?.space?.uid,
          hash: uploadConfig?.data?.swfconfig?.hash,
        }}
        name="Filedata"
        controlled
        onChange={(value) => {
          setMaterial(value);
        }}
        value={material}
      />
      {/* <div className={styles.top}>
        <div>
          <div>
            <span>课程素材：</span>
            <Radio.Group value={materialType} onChange={onMaterialTypeChange} className="c-radio">
              <Radio value="本地上传">本地上传</Radio>
              <Radio value="网盘地址">网盘地址</Radio>
            </Radio.Group>
          </div>
          <span>超过20M的附件请使用网盘地址</span>
        </div>
        <div style={{ marginTop: 10 }}>
          {materialType === '本地上传' &&
            (loading ? (
              <div style={{ height: '50px' }} />
            ) : (
              <ProcessBarUpload
                action={apiUrl}
                payload={{
                  mod: 'swfupload',
                  ac: 'course',
                  field: 'attach',
                  classid,
                  version: 'pc1.0',
                  uid: uploadConfig?.data?.space?.uid,
                  hash: uploadConfig?.data?.swfconfig?.hash,
                }}
                onBeforeUpload={handleSucaiBeforeUpload}
                className={styles.shucai}
                tips="点击上传课程素材（zip，rar）"
                prefix={<i className="icon-file-link" />}
                style={{ width: '100%' }}
                name="Filedata"
                onSuccess={handleSucaiZIpUploadSuccess}
                value={zipUploadRef.current}
              />
            ))}
          {materialType === '网盘地址' && (
            <Input.TextArea
              className={styles.wangpan}
              value={wangPanUrl.url}
              onChange={handleWangpanUrlChange}
              placeholder="请输入网盘链接及提取码"
              onBlur={handleUploadWangpanUrl}
              autoSize={{ minRows: 1, maxRows: 4 }}
            />
          )}
        </div>
      </div> */}
      {/* upload buttons */}
      {/*
        * 隐藏
        <div className={styles.buttons}>
        <i className={styles.img} />
        <span className={styles.tips}>请为课程添加课时视频</span>

        <BjyVideoListModalUpload
          action=""
          payload={{ classid, createlesson: 1 }}
          getPlvAuth={auth}
          refreshPlvAuth={auth}
          onSuccess={handleUploadSuccess}
        >
          <div className={styles.button}>
            <div className={styles.icon} />
            <div className={styles.text}>上传本地视频</div>
          </div>
        </BjyVideoListModalUpload>

        <Tooltip
          placement="bottom"
          trigger="click"
          overlayClassName="c-tooltip"
          overlayInnerStyle={{ width: 570, overflow: 'hidden' }}
          visible={urlVisible}
          onVisibleChange={(visible) => {
            setUrlVisible(visible);
            setUrl(undefined);
          }}
          title={
            <div className={styles['upload-local-container']}>
              <Input value={url} onChange={(evt) => setUrl(evt.target.value)} />
              <Button onClick={onAddVideoWithUrl} style={{ width: 96, height: 44 }} type="primary">
                确定
              </Button>
            </div>
          }
        >
          <div onClick={() => setUrlVisible(true)} className={classNames(styles.button, styles.zs)}>
            <div className={styles.icon} />
            <div className={styles.text}>添加外部视频链接</div>
          </div>
        </Tooltip>
        {userInfo.isadmin == 1 && <AddForVideoLibrary onSubmit={onAddVideo} />}
      </div>*/}
      {/* 表格 */}
      <Table
        ref={tableRef}
        loading={loading}
        dataSource={dataSource}
        reload={init}
        onSaveSort={props.onSaveSort}
        onAddVideo={onAddVideo}
      />
    </div>
  );
});

export default Index;
